﻿using System;
using System.Data;
using System.Collections;
using LogLibrary;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using Cinemon.Utils;

namespace Cinemon.MySqlConnect
{
    /// <summary>
	/// Handles connections and queries for the database
    /// </summary>
	public class DatabaseManager : IDisposable {
		protected MySqlConnection conn = new MySqlConnection(Settings.Instance.ConnectionString);

		public DataTable ExecuteQuery(string ProcedureName, List<MySqlParameter> Parameters) {
			try {
				MySqlCommand sqlCmd = new MySqlCommand(ProcedureName, conn);
				sqlCmd.CommandType = CommandType.StoredProcedure;

				if (Parameters != null) {
					foreach (MySqlParameter param in Parameters) {
						sqlCmd.Parameters.Add(param);
					}
				}

				DataTable dtReturn = new DataTable();
				conn.Open();
				MySqlDataReader sqlDR = sqlCmd.ExecuteReader();
				dtReturn.Load(sqlDR);

				return dtReturn;
			}
			catch (Exception ex) {
				WriteToLog(ex);
				return null;
			}
			finally {
				Dispose();
			}
		}

		public DataTable ExecuteQuery(string ProcedureName) {
			return ExecuteQuery(ProcedureName, null);
		}

		public void ExecuteNonQuery(string ProcedureName, List<MySqlParameter> Parameters) {
			try {
				MySqlCommand sqlCmd = new MySqlCommand(ProcedureName, conn);
				sqlCmd.CommandType = CommandType.StoredProcedure;

				foreach (MySqlParameter param in Parameters) {
					sqlCmd.Parameters.Add(param);
				}

				conn.Open();
				sqlCmd.ExecuteNonQuery();
			}
			catch (Exception ex) {
				WriteToLog(ex);
			}
			finally {
				Dispose();
			}
		}

		protected void WriteToLog(Exception ex) {
			EventLogger.Log.LogError(ex);
		}

		public void Dispose() {
			if ((conn != null) &&
				(conn.State != System.Data.ConnectionState.Closed)) {
				conn.Close();
			}
		}
	}
}
